// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
const db = cloud.database()
const _ = db.command
const limit = 100;
exports.main = async(event, context) => {
  const targetDB = db.collection(event.db)
  try {
    if (event.type == "insert") {
      return await targetDB.add({
        data: event.data
      })
    }

    if (event.type == "update") {
      return await targetDB.where(event.condition).update({
        data: event.data
      })
    }

    if (event.type == "delete") {
      return await targetDB.where(event.condition).remove()
    }
    const $ = db.command.aggregate
    if (event.type == "get2") {
      return await targetDB.aggregate()
        .group({
          time: $time,
          list: $.addToSet('$event.addtoset')
        })
        .end()
    }
    if (event.type == "get1") {
      const countResult = await targetDB.count()
      const total = countResult.total
      // 计算需分几次取
      const batchTimes = Math.ceil(total / 100)
      // 承载所有读操作的 promise 的数组
      const tasks = []
      for (let i = 0; i < batchTimes; i++) {
        const promise = targetDB.where(event.condition).field(event.field).skip(i * limit).limit(limit).orderBy('time', 'desc').get()
        tasks.push(promise)
      }
      // 等待所有
      return (await Promise.all(tasks)).reduce((acc, cur) => {
        return {
          data: acc.data.concat(cur.data),
          errMsg: acc.errMsg,
        }
      })
      // return await tasks;
    }
    if (event.type == "get") {
      const countResult = await targetDB.count()
      const total = countResult.total
      // 计算需分几次取
      const batchTimes = Math.ceil(total / 100)
      // 承载所有读操作的 promise 的数组
      const tasks = []
      for (let i = 0; i < batchTimes; i++) {
        const promise = targetDB.where(event.condition).field(event.field).skip(i * limit).limit(limit).get()
        tasks.push(promise)
      }
      // 等待所有
      return (await Promise.all(tasks)).reduce((acc, cur) => {
        return {
          data: acc.data.concat(cur.data),
          errMsg: acc.errMsg,
        }
      })
      // return await tasks;
    }
  } catch (e) {
    console.error(e)
  }
}